<template>
  <div class="app-container">
    <el-form
      ref="ruleFormRef"
      :model="role"
      :rules="validateRules"
      label-width="120px"
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="role.roleName" />
      </el-form-item>
      <el-form-item>
        <el-button
          :disabled="saveBtnDisabled"
          type="primary"
          @click="saveOrUpdate(ruleFormRef)"
        >
          保存
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { onBeforeMount, ref, watch } from 'vue'
import { ElMessage, FormInstance } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import roleApi from '@/api/acl/role'
import useCloseTag from "@/hooks/useCloseTag"

const { closeTag } = useCloseTag()
const defaultForm = {
  id: '',
  roleName: '',
}
const role = ref(defaultForm)

// 表单校验规则
const validateRules = {
  roleName: [{ required: true, trigger: 'blur', message: '角色名必须输入' }],
}

// 表单数据和保存按钮状态
const ruleFormRef = ref<FormInstance>()
const saveBtnDisabled = ref(false)

// 路由相关
const $route = useRoute()

// 初始化表单
const init = () => {
  if ($route.params && $route.params.id) {
    const id = $route.params.id as string
    fetchDataById(id)
  } else {
    role.value = { ...defaultForm }
  }
}


onBeforeMount(() => {
  console.log('form created ......')
  init()
})

// 监听器
watch($route, (to, from) => {
  console.log('路由变化......')
  console.log(to)
  console.log(from)
  init()
})

// 新增或更新讲师
const saveOrUpdate = (formRef: FormInstance) => {
  formRef.validate((valid: boolean) => {
    if (valid) {
      saveBtnDisabled.value = true // 防止表单重复提交
      if (!role.value.id) {
        saveData()
      } else {
        updateData()
      }
    }
  })
}

// 新增角色
const saveData = () => {
  roleApi
    .save({
      roleName: role.value.roleName,
    })
    .then(response => {
      
        ElMessage({
          type: 'success',
          message: response.message,
        })
        closeTag.value()
      
    })
}

// 根据id更新记录
const updateData = () => {
  roleApi.updateById(role.value).then(response => {
   
      ElMessage({
        type: 'success',
        message: response.message,
      })
      closeTag.value()
    
  })
}

// 根据id查询记录
const fetchDataById = (id: string) => {
  roleApi.getById(id).then(response => {
    role.value = response.data
  })
}
</script>